package com.flower.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.flower.config.AliyunOss;
import com.flower.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName UploadServiceImpl
 * @Description TODO
 * @Author 吃麻椒的花酱
 * @Date 2022/3/16 11:40
 * @Version 1.0
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    // 创建OSSClient实例。


    @Override
    public String uploadFile(MultipartFile file) {
        OSS ossClient=null;
        try {
            ossClient=new OSSClientBuilder().build(AliyunOss.ENDPOINT, AliyunOss.ASSESS_KEY_ID, AliyunOss.ASSESS_KEY_SECRET);
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream =file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String filename= RandomStringUtils.randomAlphanumeric(6)+originalFilename.substring(originalFilename.indexOf('.'));
            String date = new DateTime().toString("yyyy/MM/dd");
            String fileName=date+"/"+filename;
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(AliyunOss.BUCKET_NAME, fileName, inputStream);

            String url = "https://"+AliyunOss.BUCKET_NAME+"."+AliyunOss.ENDPOINT+"/"+fileName;
            return  url;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            assert ossClient != null;
            ossClient.shutdown();
        }
        return null;


    }

    @Override
    public void deleteFile(String url) {
        OSS ossClient = new OSSClientBuilder().build(AliyunOss.ENDPOINT, AliyunOss.ASSESS_KEY_ID, AliyunOss.ASSESS_KEY_ID);
         log.info(url + "---------------");
         // 截取文件名
        String filePath = url.substring(48);
        log.info(filePath);
        ossClient.deleteObject(AliyunOss.BUCKET_NAME, filePath);
        ossClient.shutdown();
    }
}
